<script setup>
import { ref, onUnmounted, nextTick } from "vue";
import { send } from "@/services/login";
import { updatePhone, checkPhone } from "@/services/setting";
import { useUserStore } from "@/stores/user.js";

// import { share } from "@/utils/share.js";

const popup = ref(null);

const user = useUserStore();

// 获取组件实例
const formRef = ref(null);

// 表单数据
const formData = ref({
  phone: "",
  code: "",
  referrer_id: uni.getStorageSync("referrer_id")
    ? uni.getStorageSync("referrer_id")
    : 0,
});
const valiForm = ref(null);

// 验证表单数据的规则
const formRules = {
  phone: {
    rules: [
      {
        required: true,
        errorMessage: "请填写手机号码",
      },
      {
        pattern: "^1\\d{10}$",
        errorMessage: "手机号码格式不正确",
      },
    ],
  },
  code: {
    rules: [
      {
        required: true,
        errorMessage: "请输入验证码",
      },
      {
        pattern: /^\S{6}$/,
        errorMessage: "请输入6位数验证码",
      },
    ],
  },
};

/* 手机号校验规则*/
const rules = ref({
  phone: {
    rules: [
      {
        required: true,
        errorMessage: "手机号不能为空",
      },
      {
        validateFunction: function (rule, value, data, callback) {
          let iphoneReg = /^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/; //手机号码
          if (!iphoneReg.test(value)) {
            callback("手机号码格式不正确，请重新填写");
          }
        },
      },
    ],
  },

  code: {
    rules: [
      {
        required: true,
        errorMessage: "手机验证码不能为空",
      },
    ],
  },
});

// 跳转页面
async function formSubmit() {
  if (!valiFormData.value.phone && !valiFormData.value.code) return;
  valiFormData.value.check_code = check_code.value;
  try {
    valiForm.value
      .validate(["phone"])
      .then(async (res) => {
        try {
          const datas = await updatePhone(valiFormData.value);
          if (datas.code === 200) {
            uni.removeStorageSync("Authorization");
            uni.showToast({
              title: "修改成功",
              icon: "success",
              mask: true,
            });
            setTimeout(() => {
              uni.reLaunch({
                url: "/pages/login/login",
              });
            }, 1500);
          } else {
            uni.showToast({
              title: datas.info,
              icon: "none",
            });
          }
        } catch (e) {
          uni.showToast({
            title: e.info,
            icon: "none",
          });
        }
      })
      .catch((e) => {
        uni.showToast({
          title: e[0].errorMessage,
          icon: "none",
        });
      });

    // 临时跳转到首页面
  } catch (e) {
    //TODO handle the exception
  }
}

// 跳转页面
async function oldSubmit() {
  if (!user.userInfo.phone && !old_code) return;
  try {
    let res = await checkPhone({ code: old_code.value });
    ischeck.value = true;
    check_code.value = res.data.check_code;
    uni.showToast({
      title: res.info,
      icon: "success",
      mask: true,
    });
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
      mask: true,
    });
  }
}

//认证码模块
let timeget = null;
const timenum = ref(60);
const codedisabled = ref(false);

//旧手机号模块
let timegetold = null;
const timenumold = ref(60);
const codedisabledold = ref(false);
const ischeck = ref(false);
const old_code = ref("");
const check_code = ref("");

/* 旧手机号 */
const getcodesold = async () => {
  if (codedisabledold.value) {
    return;
  }
  valiForm.value
    .validateField(["old_phone"])
    .then(async (ress) => {
      codedisabledold.value = true;

      timegetold = setInterval(function () {
        timenumold.value--;
        if (timenumold.value <= 0) {
          codedisabledold.value = false;
          clearInterval(timegetold);
          timenumold.value = 60;
        }
      }, 1000);
      uni.removeStorageSync("jwt-token");
      const res = await send({
        phone: user.userInfo.phone,
      });
    })
    .catch((err) => {});
};

/* 发送手机号 */
const getcodes = async () => {
  if (codedisabled.value) {
    return;
  }
  valiForm.value
    .validateField(["phone"])
    .then(async (ress) => {
      codedisabled.value = true;

      timeget = setInterval(function () {
        timenum.value--;
        if (timenum.value <= 0) {
          codedisabled.value = false;
          clearInterval(timeget);
          timenum.value = 60;
        }
      }, 1000);
      uni.removeStorageSync("jwt-token");
      const res = await send({
        phone: user.userInfo.phone,
      });
      // formData.value.code = res.result.code
    })
    .catch((err) => {});
};
onUnmounted(() => {
  // 做一些清理工作
  clearInterval(timeget);
});

/* 权限跳转 */
const goabout = (index) => {
  if (index === 2) {
    uni.navigateTo({
      url: "/pages/privacypolicy/index",
    });
  } else {
    uni.navigateTo({
      url: "/pages/userpermiss/index",
    });
  }
};
const checked = ref(false);

/* 勾选是否阅读权限 */
const checkboxfun = () => {
  checked.value = !checked.value;
};

/* 基础表单数据 */
const valiFormData = ref({
  phone: "",
  code: "",
});

// #ifdef MP-WEIXIN
const title = ref("用户隐私保护提示");
const desc1 = ref("感谢您使用私语清韵小程序，您使用本小程序前应当阅井同意");
const urlTitle = ref("《用户隐私保护指引》");
const desc2 = ref(
  "当您点击同意并开始时用产品服务时，即表示你已理解并同息该条款内容，该条款将对您产生法律约束力。如您拒绝，将无法正常使用该小程序。"
);

if (uni.getPrivacySetting) {
  uni.getPrivacySetting({
    success: (res) => {
      if (res.needAuthorization) {
        nextTick(() => {
          setTimeout(() => {
            popup.value.open("center");
          }, 1);
        });
      } else {
      }
    },
    fail: () => {},
    complete: () => {},
  });
} else {
  // 低版本基础库不支持 wx.getPrivacySetting 接口，隐私接口可以直接调用
}
// #endif

const openPrivacyContract = () => {
  uni.openPrivacyContract({
    success: (res) => {},
    fail: (res) => {
      console.error("openPrivacyContract fail", res);
    },
  });
};
const handleAgree = () => {
  popup.value.close();
};
const handleDisagree = (e) => {
  popup.value.close();
  uni.navigateBack({
    delta: 1,
  });
};
</script>
<template>
  <view class="login">
    <view class="bg">
      <div class="ul-img">
        <!-- <image src="../../static/home/tab_me_n.png" mode="widthFix"></image> -->
      </div>
      <view class="ul">
        <view class="li"> </view>
      </view>
      <view class="login-item-title">{{
        ischeck ? "更改新手机号" : "旧手机号验证"
      }}</view>
    </view>
    <view class="login-bottom" v-if="!ischeck">
      <view class="mobile">
        <view class="form-k">
          <uni-forms
            ref="valiForm"
            :rules="rules"
            :modelValue="valiFormData"
            label-width="80"
          >
            <view class="imfrom-k">
              <view class="imfrom-k-icon">
                <image
                  src="@/pages/mysetting/static/login/login_phone.png"
                  mode="widthFix"
                />
              </view>
              <uni-forms-item label="" name="old_phone">
                <uni-easyinput v-model="user.userInfo.phone" disabled />
              </uni-forms-item>
            </view>

            <view class="imfrom-k">
              <view class="imfrom-k-icon">
                <image
                  src="@/pages/mysetting/static/login/login_code.png"
                  mode="widthFix"
                />
              </view>
              <uni-forms-item label="" name="old_code">
                <view class="imfrom-k-yz">
                  <view class="imfrom-inputs">
                    <uni-easyinput
                      v-model="old_code"
                      placeholder="请输入验证码"
                    >
                      <template #right>
                        <view class="getcodes" @click="getcodesold">
                          <text :class="codedisabledold ? 'selectcodes' : ''">{{
                            codedisabledold
                              ? timenumold + "s后重新获取"
                              : "获取验证码"
                          }}</text>
                        </view>
                      </template>
                    </uni-easyinput>
                  </view>
                </view>
              </uni-forms-item>
            </view>
          </uni-forms>
        </view>
      </view>
      <!-- <view class="zc-rule">
        <checkbox-group @change="checkboxfun">
          <label>
            <view class="zc-rule-checkox">
              <checkbox
                value="cb"
                :checked="false"
                color="#b63434"
                style="transform: scale(0.7)"
              />
            </view>
          </label>
        </checkbox-group>
        <view class="zc-rule-name">
          <text>我已阅读同意</text
          ><text class="text-color" @click="goabout(3)">《用户协议》</text
          >、<text class="text-color" @click="goabout(2)">《隐私政策》</text>
        </view>
      </view> -->
      <button
        class="uni-button"
        :class="user.userInfo.phone && old_code ? 'uni-button-cloor' : ''"
        @click="oldSubmit"
      >
        验证
      </button>
      <!-- <view class="unilogin-dec">如何成为经销商？</view> -->
    </view>
    <view class="login-bottom" v-if="ischeck">
      <view class="mobile">
        <view class="form-k">
          <uni-forms
            ref="valiForm"
            :rules="rules"
            :modelValue="valiFormData"
            label-width="80"
          >
            <view class="imfrom-k">
              <view class="imfrom-k-icon">
                <image
                  src="@/pages/mysetting/static/login/login_phone.png"
                  mode="widthFix"
                />
              </view>
              <uni-forms-item label="" name="phone">
                <uni-easyinput
                  v-model="valiFormData.phone"
                  placeholder="请输入新手机号码"
                />
              </uni-forms-item>
            </view>

            <view class="imfrom-k">
              <view class="imfrom-k-icon">
                <image
                  src="@/pages/mysetting/static/login/login_code.png"
                  mode="widthFix"
                />
              </view>
              <uni-forms-item label="" name="code">
                <view class="imfrom-k-yz">
                  <view class="imfrom-inputs">
                    <uni-easyinput
                      v-model="valiFormData.code"
                      placeholder="请输入验证码"
                    >
                      <template #right>
                        <view class="getcodes" @click="getcodes">
                          <text :class="codedisabled ? 'selectcodes' : ''">{{
                            codedisabled
                              ? timenum + "s后重新获取"
                              : "获取验证码"
                          }}</text>
                        </view>
                      </template>
                    </uni-easyinput>
                  </view>
                </view>
              </uni-forms-item>
            </view>
          </uni-forms>
        </view>
      </view>
      <button
        class="uni-button"
        :class="
          valiFormData.phone && valiFormData.code ? 'uni-button-cloor' : ''
        "
        @click="formSubmit"
      >
        确定修改
      </button>
    </view>
  </view>

  <!-- #ifdef MP-WEIXIN -->
  <uni-popup ref="popup" :animation="true" :is-mask-click="false">
    <view class="popup_content">
      <view class="popup_title">
        {{ title }}
      </view>
      <view class="popup_desc">
        {{ desc1 }}
      </view>
      <view class="popup_urlTitle" @click="openPrivacyContract">
        {{ urlTitle }}
      </view>
      <view class="popup_desc">
        {{ desc2 }}
      </view>
      <view class="popup_cz">
        <button
          id="disagree-btn"
          type="default"
          class="weui-btn"
          @click="handleDisagree"
        >
          不同意并退出
        </button>
        <button
          id="agree-btn"
          type="primary"
          open-type="agreePrivacyAuthorization"
          class="weui-btn"
          @agreeprivacyauthorization="handleAgree"
        >
          同意并继续
        </button>
      </view>
    </view>
  </uni-popup>
  <!-- #endif -->
</template>

<style lang="scss" scoped>
@import "index.scss";
</style>
